package com.dx.mes.service.warehouse.service;

import com.dx.common.table.ppt.Ret_prd_in;
import com.dx.common.table.ppt.Ret_prd_indt;
import com.dx.mes.common.dao.IRetPrdInDao;
import com.dx.mes.common.dao.IRetPrdIndtDao;
import com.dx.mes.common.dao.IRetWhMtrlDao;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.warehouse.service.IMwpmtrlopeService;
import com.dx.mes.facade.warehouse.service.IMwpwhsmtrlService;
import com.dx.mes.facade.warehouse.tx.Mwpmtrlope.MwpmtrlopeI;
import com.dx.mes.facade.warehouse.tx.Mwpmtrlope.MwpmtrlopeO;
import com.dx.mes.facade.warehouse.tx.Mwpwhsmtrl.MwpwhsmtrlI;
import com.dx.mes.facade.warehouse.tx.Mwpwhsmtrl.MwpwhsmtrlIA;
import com.dx.mes.facade.warehouse.tx.Mwpwhsmtrl.MwpwhsmtrlO;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dx.mes.common.bean.def.GenericDef.*;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;

/**
 * Created by admin on 2018/3/13.
 */
@Service("mwpwhsmtrlService")
public class MwpwhsmtrlService implements IMwpwhsmtrlService {
    private LogUtils logUtils;
    private static String TX_NAME = T_MWPWHSMTRL;

    @Autowired
    private IRetPrdIndtDao   retPrdIndtDao;
    @Autowired
    private IRetPrdInDao     retPrdInDao;

    @Override
    public String subMainProc(String evt_no, String strInTrx) {
        AppContext.clear();
        AppContext.setCurrServiceName(MwpwhsmtrlService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(MwpwhsmtrlService.class);
        logUtils.info("[InTrx:" + strInTrx + "]");

        Session session = retPrdIndtDao.getCrSession();
        long rtnCode = _NORMAL;
        String outMsg = null;

        MwpwhsmtrlI inTrx  = new MwpwhsmtrlI();
        MwpwhsmtrlO outTrx = new MwpwhsmtrlO();
        outTrx.setTrx_id(TX_NAME);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
        outTrx.setType_id(TRX_OUT);
        try {
            inTrx = JacksonUtil.fromJson(strInTrx, MwpwhsmtrlI.class);

            rtnCode = subMainProc2(inTrx, outTrx);
            if (rtnCode != _NORMAL) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                outTrx.setRtn_code(String.valueOf(rtnCode));
            } else {
                outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
                outTrx.setRtn_mesg(RETURN_MESG_OK);
                session.flush();
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            outTrx.setRtn_mesg(ex.toString());
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            logUtils.error(Util.stackTraceToString(ex));
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outMsg + "]");
        }
        return outMsg;
    }

    private long subMainProc2(MwpwhsmtrlI inTrx, MwpwhsmtrlO outTrx) {
        long lRc = _NORMAL;
        char actionType = inTrx.getAction_flg().toCharArray()[0];
        switch (actionType) {
            case 'A': {
                lRc = saveFunc(inTrx, outTrx);
                if (lRc != _NORMAL) {
                    return lRc;
                }
                break;
            }
            default: {
                outTrx.setRtn_mesg("Invalide type input: [" + actionType + "]");
                return E_MWPMTROPE_INVALID_INPUT;
            }
        }
        return lRc;
    }
    private long saveFunc(MwpwhsmtrlI inTrx, MwpwhsmtrlO outTrx) {
        long lRc = _NORMAL;
        Timestamp gEvtTimestamp = Util.getCurrentTimestamp();
        List<MwpwhsmtrlIA> irayList = inTrx.getIary();
        List<Ret_prd_indt>  prdIndtList = new ArrayList<>();
        Map<Ret_prd_in, Integer> map = new HashMap<Ret_prd_in, Integer>();
        for (MwpwhsmtrlIA mwpwhsmtrlIA : irayList) {
            Ret_prd_indt ret_prd_indt = new Ret_prd_indt();
            ret_prd_indt.setVdr_prd_seq_id(mwpwhsmtrlIA.getVrd_prd_seq_id());
            ret_prd_indt.setUnq_seq_id(GUIDGenerator.javaGUID());
            //ret_prd_indt.setPrd_stat();
            ret_prd_indt.setMtrl_box_id_fk(mwpwhsmtrlIA.getMtrl_box_id());
            //ret_prd_indt.setMtrl_slot_no();
            ret_prd_indt.setMtrl_grade(mwpwhsmtrlIA.getMtrl_grade());
            //ret_prd_indt.setChip_grade();
            ret_prd_indt.setMtrl_def_code(mwpwhsmtrlIA.getMtrl_def_code());
            ret_prd_indt.setEvt_usr(inTrx.getEvt_usr());
            ret_prd_indt.setEvt_timestamp(gEvtTimestamp);


            //构造箱子信息
            Ret_prd_in  ret_prd_in = new Ret_prd_in();
            ret_prd_in.setMtrl_box_id(mwpwhsmtrlIA.getMtrl_box_id());
            ret_prd_in.setUnq_seq_id(GUIDGenerator.javaGUID());
            ret_prd_in.setBox_cate(mwpwhsmtrlIA.getBox_cate());
            //ret_prd_in.setVdr_box_id();
            ret_prd_in.setCus_id_fk(mwpwhsmtrlIA.getCus_id_fk());
            ret_prd_in.setMtrl_pallet_id(mwpwhsmtrlIA.getMtrl_pallet_id());
            ret_prd_in.setMtrl_lot_id(mwpwhsmtrlIA.getMtrl_lot_id());
            //ret_prd_in.setPpbox_stat();
            ret_prd_in.setMtrl_prod_id_fk(mwpwhsmtrlIA.getMtrl_prod_id());
            //ret_prd_in.setMtrl_gd();
            //ret_prd_in.setMtrl_thickness();
            ret_prd_in.setStb_shop(mwpwhsmtrlIA.getStb_shop());
            ret_prd_in.setStorage_loc(mwpwhsmtrlIA.getStorage_loc());
            //ret_prd_in.setPrd_tl_qty();
            //ret_prd_in.setPrd_act_qty();
            //ret_prd_in.setPrd_act_qty();
            //ret_prd_in.setBox_weight();
            ret_prd_in.setCrt_usr(mwpwhsmtrlIA.getCrt_usr());
            if(!Util.isSpaceCheck(mwpwhsmtrlIA.getCrt_timestamp())){
                ret_prd_in.setCrt_timestamp(Timestamp.valueOf(mwpwhsmtrlIA.getCrt_timestamp()));
            }
            ret_prd_in.setEvt_cate("");
            ret_prd_in.setEvt_usr(inTrx.getEvt_usr());
            ret_prd_in.setEvt_timestamp(gEvtTimestamp);
            if(map.containsKey(ret_prd_in)){
               map.put(ret_prd_in,map.get(ret_prd_in)+1);
            }else{
                map.put(ret_prd_in,1);
            }
            prdIndtList.add(ret_prd_indt);
        }


        retPrdIndtDao.saveOrUpdateAll(prdIndtList);
        for (Map.Entry<Ret_prd_in, Integer> entry : map.entrySet()) {
            retPrdInDao.saveOrUpdate(entry.getKey());
        }
        return lRc;
    }
}
